package com.sptus.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sptus.aop.AppIntercept;
import com.sptus.common.constant.CommonConstant;
import com.sptus.common.core.redis.RedisCache;
import com.sptus.system.utils.GmailSendVerificationCode;
import com.sptus.common.utils.JwtUtil;
import com.sptus.common.utils.ip.IpUtils;
import com.sptus.common.vo.ProblemFeedbackVo;
import com.sptus.config.DataLoaderConfig;
import com.sptus.entity.SptUser;
import com.sptus.framework.annotation.AutoLog;
import com.sptus.model.SysLoginModel;
import com.sptus.service.IAppEquipmentService;
import com.sptus.service.ISptUserService;
import com.sptus.system.domain.ConfigInfo;
import com.sptus.system.domain.Equipment;
import com.sptus.system.service.IConfigInfoService;
import com.sptus.util.CryptUtil;
import com.sptus.util.DySmsLimit;
import com.sptus.util.JWTutil;
import com.sptus.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
@RestController
@Api(tags = "app用户接口")
@RequestMapping("/sys/app/user")
public class AppUserController {
    @Autowired
    ISptUserService sptUserService;
    @Autowired
    private IAppEquipmentService equipmentService;

    @Autowired
    private IConfigInfoService configInfoService;
    public static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();


//    email_update_code12345@qq.com
    @AutoLog(value = "修改密码-编辑")
    @ApiOperation(value="修改密码-编辑", notes="修改密码-编辑")
    @AppIntercept
    @RequestMapping(value = "/updatePassWord", method = {RequestMethod.POST})
    public Result<String> updatePassWord(@RequestBody SptUser sptUser) {
        Result<String> result = new Result<>();
        LambdaQueryWrapper<SptUser> sptUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserLambdaQueryWrapper.eq(SptUser::getId,sptUser.getId());

        SptUser sptUser1 = sptUserService.getBaseMapper().selectOne(sptUserLambdaQueryWrapper);
        boolean b = CryptUtil.checkTruePassword(sptUser.getPassword(), sptUser1.getPassword());
        if(!b){
           return result.error500("Old password error");
       }
        sptUser.setUpdatedAt(new Date());
        sptUser.setIsInit(1);
        SptUser sptUser2 = new SptUser();

        sptUser2.setPassword(CryptUtil.encodedPassword(sptUser.getConfirmPassword()));
        boolean update = sptUserService.update(sptUser2, sptUserLambdaQueryWrapper);
        result.setCode(200);
        return result;
    }

    @PostMapping ("/updateGmailCode")
    @ApiOperation(value="修改邮箱验证码", notes="获取code注册")
    @AppIntercept
    public Result<JSONObject> updateGmailCodeLogin(@RequestBody SptUser  user, HttpServletRequest request) {
        Result<JSONObject> result = new Result<JSONObject>();
        String clientIp = IpUtils.getIpAddr(request);
        String redisKey = CommonConstant.EMAIL_UPDATE_CODE+user.getNewEmail();
        if(!DySmsLimit.canSendSms(clientIp)){
            log.warn("--------[警告] IP地址:{}, 短信接口请求太多-------", clientIp);
            result.setMessage("Too many SMS interface requests, please try again later!");
            result.setCode(CommonConstant.PHONE_SMS_FAIL_CODE);
            result.setSuccess(false);
            return result;
        }
        if(StringUtils.isEmpty(user.getEmail())){
            return result.error500("The mailbox cannot be empty");
        }
        LambdaQueryWrapper<SptUser> sptUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserLambdaQueryWrapper.eq(SptUser::getEmail,user.getNewEmail());

        SptUser sptUser1 = sptUserService.getBaseMapper().selectOne(sptUserLambdaQueryWrapper);
        if(!ObjectUtil.isEmpty(sptUser1)){
            return result.error500("email already exists");
        }
        String captcha = RandomUtil.randomNumbers(6);
        redisUtil.setCacheObject(redisKey, captcha, 600, TimeUnit.SECONDS);
        String to = user.getNewEmail(); // 收件人邮箱
        String from = DataLoaderConfig.getGlobalData().get("spt.auth.code.email") ; // 发件人邮箱（你的Gmail）
        String host = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.host") ; // SMTP服务器地址
        String port =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.post"); // Gmail SMTP端口
        // 生成验证码（这里仅为示例）
        String verificationCode = captcha;
        // Gmail用户名和密码（或使用应用专用密码）
        String username =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.username");
        String password = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.pass");
        try {
            cachedThreadPool.submit(new Thread(new Runnable() {
                @Override
                public void run() {
                    GmailSendVerificationCode.sendEmailWithVerificationCode(to, verificationCode, from, host, port, username, password,clientIp);
                }
            }));
            result.setSuccess(true);
        }catch (Exception e){
            //自定义异常

        }finally {

        }
        if (!result.isSuccess()) {
            return result.error500("unsent messages");
        }
        return result.success("Message sent successfully");

    }

    @PostMapping ("/updateGmailCodeLogin")
    @ApiOperation(value="修改邮箱", notes="获取code注册")
    @AppIntercept
    public Result<JSONObject> updateGmailCodeLogin(@RequestBody SptUser  user ){
        Result<JSONObject>  result=new Result<>();
        Object o = redisUtil.getCacheObject(CommonConstant.EMAIL_UPDATE_CODE + user.getNewEmail());
        if(StringUtils.isEmpty(o)){
            return result.error500("code error");
        }

        if(!o.equals(user.getSmscode())){
            return result.error500("code error");
        }
        redisUtil.deleteObject(CommonConstant.EMAIL_UPDATE_CODE + user.getNewEmail());
        LambdaQueryWrapper<SptUser> sptUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserLambdaQueryWrapper.eq(SptUser::getId,user.getId());
        SptUser sptUser = new SptUser();
        sptUser.setEmail(user.getNewEmail());
        boolean update = sptUserService.update(sptUser, sptUserLambdaQueryWrapper);
        return result.success("update successfully");
    }



    @GetMapping("/getUser")
    @ApiOperation(value="通过token获得用信息", notes="equipment-添加")
    @AppIntercept
    public Result<Object> getUser(SptUser sptUser){
        Result<Object> result = new Result<>();
        Integer id = sptUser.getId();
        LambdaQueryWrapper<SptUser> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(SptUser::getId,id);
        SptUser sptUserInfo = sptUserService.getOne(objectLambdaQueryWrapper);

//        SptUser sptUserInfo = sptUserService.getBaseMapper().selectOne(objectLambdaQueryWrapper);
        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSignBy,sptUser.getId());
        List<Equipment> equipmentlist = equipmentService.getBaseMapper().selectList(equipmentLambdaQueryWrapper);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("equipmentExist",equipmentlist.size()>0);
        stringObjectHashMap.put("userInfo",sptUserInfo);

        List<Equipment> collect = equipmentlist.stream().filter(e -> !e.getStatus().equals("2")).collect(Collectors.toList());
        stringObjectHashMap.put("networkExist",collect.size()>0);
        stringObjectHashMap.put("updateUser", !ObjectUtil.isEmpty(sptUserInfo.getUpdatedAt()));
        result.setResult(stringObjectHashMap);
        return result.success("Query success");
    }



    @PostMapping("/problemFeedback")
    @ApiOperation(value="问题反馈", notes="equipment-添加")
    @AppIntercept
    public Result<Object> problemFeedback(@RequestBody ProblemFeedbackVo problemFeedbackVo, SptUser sptUser){
        Result<Object> result = new Result<>();
        LambdaQueryWrapper<ConfigInfo> configInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        configInfoLambdaQueryWrapper.in(ConfigInfo::getName,"spt.receive.email");
        problemFeedbackVo.setEmail(sptUser.getEmail());
        ConfigInfo configInfo = configInfoService.getBaseMapper().selectOne(configInfoLambdaQueryWrapper);
        String to = configInfo.getValue(); // 收件人邮箱
        String from = "yunji.yuan@sptcssc.com"; // 发件人邮箱（你的Gmail）
        String host = "smtp.gmail.com"; // SMTP服务器地址
        String port = "587"; // Gmail SMTP端口
        // 生成验证码（这里仅为示例）

        // Gmail用户名和密码（或使用应用专用密码）
        String username = "yunji.yuan@sptcssc.com";
        String password = "pyhtxvljmmezupyn";
        try {
            cachedThreadPool.submit(new Thread(new Runnable() {
                @Override
                public void run() {
                    GmailSendVerificationCode.sendProblemFeedback(to,problemFeedbackVo, from, host, port, username, password);
                }
            }));
            result.setSuccess(true);
        }catch (Exception e){
            //自定义异常

        }finally {

        }
        return result.success("Query success");
    }
    @AutoLog(value = "用户编辑-编辑")
    @ApiOperation(value="用户编辑-编辑", notes="spt_user-编辑")
    @AppIntercept
    @RequestMapping(value = "/edit", method = {RequestMethod.POST})
    public Result<String> edit(@RequestBody SptUser sptUser) {
        if(!StringUtils.isEmpty(sptUser.getPassword())){
            sptUser.setPassword(CryptUtil.encodedPassword(sptUser.getPassword()));
        }

        LambdaQueryWrapper<SptUser> sptUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserLambdaQueryWrapper.eq(SptUser::getId,sptUser.getId());

        sptUser.setUpdatedAt(new Date());
        sptUser.setIsInit(1);
        sptUser.setEmail(null);
        boolean update = sptUserService.update(sptUser, sptUserLambdaQueryWrapper);

        return Result.OK("return boolean!");
    }

    @ApiOperation("邮箱发送登录验证码")
    @RequestMapping(value = "/sendEmailLogin", method = RequestMethod.POST)
    public Result<JSONObject> sendEmailLogin(@RequestBody SptUser user, HttpServletRequest request) {
        Result<JSONObject> result = new Result<JSONObject>();
        String clientIp = IpUtils.getIpAddr(request);

        String redisKey = CommonConstant.EMAIL_LOGIN_KEY_PRE+user.getEmail();
        if(!DySmsLimit.canSendSms(clientIp)){
            log.warn("--------[警告] IP地址:{}, 短信接口请求太多-------", clientIp);
            result.setMessage("Too many SMS interface requests, please try again later!");
            result.setCode(CommonConstant.PHONE_SMS_FAIL_CODE);
            result.setSuccess(false);
            return result;
        }
        if(StringUtils.isEmpty(user.getEmail())){
            return result.error500("The mailbox cannot be empty");
        }
        String captcha = RandomUtil.randomNumbers(6);
        redisUtil.setCacheObject(redisKey, captcha, 600,TimeUnit.SECONDS);


        String to = user.getEmail(); // 收件人邮箱
        String from = DataLoaderConfig.getGlobalData().get("spt.auth.code.email") ; // 发件人邮箱（你的Gmail）
        String host = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.host") ; // SMTP服务器地址
        String port =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.post"); // Gmail SMTP端口
        // 生成验证码（这里仅为示例）
        String verificationCode = captcha;
        // Gmail用户名和密码（或使用应用专用密码）
        String username =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.username");
        String password = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.pass");
        try {
            cachedThreadPool.submit(new Thread(new Runnable() {
                @Override
                public void run() {
                    GmailSendVerificationCode.sendEmailWithVerificationCode(to, verificationCode, from, host, port, username, password,clientIp);
                }
            }));
            result.setSuccess(true);
        }catch (Exception e){
            //自定义异常

        }finally {

        }
        if (!result.isSuccess()) {
            return result.error500("unsent messages");
        }
        return result.success("Message sent successfully");

    }
    @GetMapping ("/getFeedbackInfo")
    @ApiOperation(value="获取问题反馈邮箱,号码", notes="equipment-添加")
    @AppIntercept
    public Result<Object> getFeedbackInfo(SptUser sptUser){
        LambdaQueryWrapper<ConfigInfo> configInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        configInfoLambdaQueryWrapper.in(ConfigInfo::getName,"spt.phone","spt.receive.email","spt.value.phone");
        configInfoLambdaQueryWrapper.orderByAsc(ConfigInfo::getSort);
        List<ConfigInfo> configInfos = configInfoService.getBaseMapper().selectList(configInfoLambdaQueryWrapper);
        Result<Object> result = new Result<>();

        Map<String, ConfigInfo> map = configInfos.stream()
                .collect(Collectors.toMap(ConfigInfo::getName, Function.identity()));
        result.setResult(map);
        return result.success("Query success");
    }

    @GetMapping   ("/GetAuthenticationCode")
    @ApiOperation(value="获取code注册", notes="获取code注册")
    @AppIntercept
    public Result<Object> GetAuthenticationCode(SptUser sptUser){
        Result<Object> ok = Result.ok();
        //用户注册
        if (sptUser.getSignType().equals("google")){

        }else if (sptUser.getSignType().equals("microsoft")){

        }else if (sptUser.getSignType().equals("apple")){

        }
        //返回token
        ok.setResult(sptUser);
        return ok.success("注册成功");
    }
    @GetMapping   ("/getUserRegister")
    @ApiOperation(value="判断是否注册", notes="判断是否注册")
    public Result<Object> getUserRegister(SptUser sptUser){
        LambdaQueryWrapper<SptUser> sptUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserLambdaQueryWrapper.eq(SptUser::getEmail,sptUser.getEmail());
        List<SptUser> sptUsers = sptUserService.selectList(sptUserLambdaQueryWrapper);
        boolean b=sptUsers.size()>0;
        //返回token
        Result<Object> ok = Result.ok();
        HashMap<String, Boolean> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("isExist",b);
        ok.setResult(stringStringHashMap);
        return ok.success("");
    }
    @GetMapping ("/getCodeSignOrLogin")
    @ApiOperation(value="获取code注册存在登录", notes="获取code注册")
    @AppIntercept
    public Result<Object> getCodeSign(SptUser sptUser){
        Result<Object> ok = Result.ok();
        //用户注册
        if (sptUser.getSignType().equals("google")){

        }else if (sptUser.getSignType().equals("microsoft")){

        }else if (sptUser.getSignType().equals("apple")){

        }
        //返回token
        ok.setResult(sptUser);
        return ok.success("registered successfully");
    }

    @Autowired
    private RedisCache redisUtil;
    private boolean isLoginFailOvertimes(String username){
        String key = CommonConstant.LOGIN_FAIL + username;
        Object failTime = redisUtil.getCacheObject(key);
        if(failTime!=null){
            Integer val = Integer.parseInt(failTime.toString());
            if(val>5){
                return true;
            }
        }
        return false;
    }
    @PostMapping ("/gmailCodeLogin")
    @ApiOperation(value="邮箱验证码登录", notes="获取code注册")
//    @AppIntercept
    public Result<JSONObject> gmailCodeLogin(@RequestBody SysLoginModel sysLoginModel){
        Result<JSONObject> result = new Result<JSONObject>();
        String username = sysLoginModel.getUsername();
        if(isLoginFailOvertimes(username)){
            return result.error500("This user has failed to log in too many times, please log in again after 10 minutes!");
        }
        if(redisUtil.getCacheObject(CommonConstant.EMAIL_LOGIN_KEY_PRE+sysLoginModel.getUsername())==null){
            return result.error500("Please obtain the verification code first");
        }
        if( !redisUtil.getCacheObject(CommonConstant.EMAIL_LOGIN_KEY_PRE+sysLoginModel.getUsername()).equals(sysLoginModel.getCaptcha())){
            return result.error500("Verification code error");
        }

        LambdaQueryWrapper<SptUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SptUser::getEmail, username);
        SptUser one = sptUserService.getOne(queryWrapper);
        if(one==null){
            one = new SptUser();
            one.setPassword(CryptUtil.encodedPassword("sptUser"));
            one.setEmail(sysLoginModel.getUsername());
            one.setNickname(sysLoginModel.getUsername());
            one.setIsMicrosoftAuth(0);
            one.setIsGoogleAuth(0);
            one.setIsAppleAuth(0);
            one.setCreatedAt(new Date());
            sptUserService.save(one);
        }
        String token = JwtUtil.sign(username, sysLoginModel.getCaptcha());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",token);
        one.setPassword("");
        jsonObject.put("userinfo",one);
        //设置 token
        redisUtil.deleteObject(CommonConstant.EMAIL_LOGIN_KEY_PRE+sysLoginModel.getUsername());
        redisUtil.setCacheObject(CommonConstant.PREFIX_EMAIL_USER_TOKEN+token,one);
        //获取用户数据设备数据
        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSignBy,one.getId());
        List<Equipment> equipmentlist = equipmentService.getBaseMapper().selectList(equipmentLambdaQueryWrapper);
        jsonObject.put("equipmentExist",equipmentlist.size()>0);
        List<Equipment> collect = equipmentlist.stream().filter(e -> !e.getStatus().equals("2")).collect(Collectors.toList());
        jsonObject.put("networkExist",collect.size()>0);
        jsonObject.put("updateUser", !ObjectUtil.isEmpty(one.getUpdatedAt()));
        result.setResult(jsonObject);
        result.isSuccess();
        return result.success("登录成功");
    }
    @PostMapping ("/GoogleLogin")
    @ApiOperation(value="谷歌登录", notes="谷歌验证码登录")
//    @AppIntercept
    public Result<JSONObject> GoogleLogin(@RequestBody SysLoginModel sysLoginModel){
        Result<JSONObject> result = new Result<JSONObject>();
        String username = sysLoginModel.getUsername();

        if(isLoginFailOvertimes(username)){
            return result.error500("This user has failed to log in too many times, please log in again after 10 minutes!");
        }

        LambdaQueryWrapper<SptUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SptUser::getEmail, username);
        SptUser one = sptUserService.getOne(queryWrapper);
        if(one==null){
            one = new SptUser();
            one.setPassword(CryptUtil.encodedPassword("sptUser"));
            one.setEmail(sysLoginModel.getUsername());
            one.setNickname(sysLoginModel.getUsername());
            one.setCreatedAt(new Date());
            sptUserService.save(one);
        }
        String token = JwtUtil.sign(username, sysLoginModel.getCaptcha());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",token);
        one.setPassword("");
        jsonObject.put("userinfo",one);
        //设置 token
        redisUtil.deleteObject(CommonConstant.EMAIL_LOGIN_KEY_PRE+sysLoginModel.getUsername());
        redisUtil.setCacheObject(CommonConstant.PREFIX_EMAIL_USER_TOKEN+token,one);
        //获取用户数据设备数据
        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSignBy,one.getId());
        List<Equipment> equipmentlist = equipmentService.getBaseMapper().selectList(equipmentLambdaQueryWrapper);
        jsonObject.put("equipmentExist",equipmentlist.size()>0);
        List<Equipment> collect = equipmentlist.stream().filter(e -> !e.getStatus().equals("2")).collect(Collectors.toList());
        jsonObject.put("networkExist",collect.size()>0);
        jsonObject.put("updateUser", !ObjectUtil.isEmpty(one.getUpdatedAt()));
        result.setResult(jsonObject);
        result.isSuccess();
        return result.success("login successfully");
    }

    @PostMapping ("/thirdPartyLogin")
    @ApiOperation(value="第三方登录", notes="第三方登录")
    public Result<JSONObject> thirdPartyLogin(@RequestBody SysLoginModel sysLoginModel) throws Exception {
        Result<JSONObject> result = new Result<JSONObject>();

        JSONObject jsonObject1 = JWTutil.parserIdentityToken(sysLoginModel.getToken(),sysLoginModel.getLoginType().toString());
        String username="";
        String email="";
        SptUser sptUser=new SptUser();
        LambdaQueryWrapper<SptUser> queryWrapper = new LambdaQueryWrapper<>();
        if(sysLoginModel.getLoginType().equals("3")){
            String sub=jsonObject1.getString("sub");
            username= jsonObject1.getString("email");
            email=jsonObject1.getString("email");
            sptUser.setNickname(username);
            sptUser.setEmail(jsonObject1.getString("email"));
            sptUser.setAppleUuid(sub);
            sptUser.setIsMicrosoftAuth(0);
            sptUser.setIsGoogleAuth(0);
            sptUser.setIsAppleAuth(1);
            queryWrapper.eq(SptUser::getAppleUuid, sub);
        }
        else if(sysLoginModel.getLoginType().equals("2")){
            String sub=jsonObject1.getString("sub");
            username= jsonObject1.getString("preferred_username");
            email= jsonObject1.getString("preferred_username");
            String name=jsonObject1.getString("name");
            sptUser.setEmail(username);
            sptUser.setNickname(name);
            sptUser.setMicrosoftUuid(sub);
            sptUser.setIsMicrosoftAuth(1);
            sptUser.setIsGoogleAuth(0);
            sptUser.setIsAppleAuth(0);
            sptUser.setMicrosoftDisplayName(name);
            queryWrapper.eq(SptUser::getMicrosoftUuid, sub);
        }else if (sysLoginModel.getLoginType().equals("1")){
            String sub=jsonObject1.getString("sub");
            username= jsonObject1.getString("name");
            email=jsonObject1.getString("email");
            sptUser.setNickname(username);
            sptUser.setGoogleUuid(sub);
            sptUser.setEmail(email);
            sptUser.setIsMicrosoftAuth(0);
            sptUser.setIsAppleAuth(0);
            sptUser.setIsGoogleAuth(1);
            queryWrapper.eq(SptUser::getGoogleUuid, sub);
        }
         if(StringUtils.isEmpty(username)){
           return result.error500("email error");
        }

        queryWrapper.or().eq(SptUser::getEmail, email);
        SptUser one = sptUserService.getOne(queryWrapper);
        if(one==null){
            sptUser.setPassword(CryptUtil.encodedPassword("sptUser"));
            sptUser.setCreatedAt(new Date());
            sptUserService.save(sptUser);
            one=sptUser;
        }else {
            sptUserService.update(sptUser,queryWrapper);
//            if(jsonObject1.get("email_verified").equals("true")){
//                if (sysLoginModel.getLoginType().equals("1")&&one.getIsGoogleAuth()==0){
//                    sptUserService.update(sptUser,queryWrapper);
//                }else  if (sysLoginModel.getLoginType().equals("1")&& one.getIsMicrosoftAuth()==0){
//                    sptUserService.update(sptUser,queryWrapper);
//                }else  if (sysLoginModel.getLoginType().equals("1")&& one.getIsAppleAuth()==0){
//                    sptUserService.update(sptUser,queryWrapper);
//                }
//            }else {
//                return result.error500("email unverified");
//            }

        }
        String token = JwtUtil.sign(username, username);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",token);
        one.setPassword("");
        jsonObject.put("userinfo",one);
        //设置 token
        redisUtil.deleteObject(CommonConstant.EMAIL_LOGIN_KEY_PRE+sysLoginModel.getUsername());
        redisUtil.setCacheObject(CommonConstant.PREFIX_EMAIL_USER_TOKEN+token,one);
        //获取用户数据设备数据
        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSignBy,one.getId());
        List<Equipment> equipmentlist = equipmentService.getBaseMapper().selectList(equipmentLambdaQueryWrapper);
        jsonObject.put("equipmentExist",equipmentlist.size()>0);
        List<Equipment> collect = equipmentlist.stream().filter(e -> !e.getStatus().equals("2")).collect(Collectors.toList());
        jsonObject.put("networkExist",collect.size()>0);
        jsonObject.put("updateUser", !ObjectUtil.isEmpty(one.getUpdatedAt()));
        result.setResult(jsonObject);
        result.isSuccess();
        return result.success("login successfully");
    }


}
